import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import HomeView from "../views/HomeView.vue";
import PrincipalSheet from "../views/PrincipalSheet.vue";
import PublishView from "../views/PublishView.vue";
import MyView from "../views/MyView.vue";
import LoginRegistration from "../views/LoginRegistration.vue";
import { showFailToast } from "vant";
const routes: Array<RouteRecordRaw> = [
    {
        path: "/",
        name: "home",
        component: HomeView,
        redirect: { name: "principalSheet" },
        children: [
            {
                path: "principalSheet",
                name: "principalSheet",
                component: PrincipalSheet,
            },
            {
                path: "my",
                name: "my",
                component: MyView,
            },
        ],
    },
    {
        path: "/publish",
        name: "publish",
        component: PublishView,
    },
    // loginRegistration
    {
        path: "/loginRegistration",
        name: "loginRegistration",
        component: LoginRegistration,
    },
    {
        path: "/set",
        name: "set",

        component: () => import("../views/SetView.vue"),
    },
    {
        path: "/articleDetails",
        name: "articleDetails",
        component: () => import("../views/ArticleDetails.vue"),
    },
    {
        path: "/myCollects",
        name: "myCollects",
        component: () => import("../views/MyCollects.vue"),
    },
    {
        path: "/myLikes",
        name: "myLikes",
        component: () => import("../views/MyLikes.vue"),
    },
    {
        path: "/myEssay",
        name: "myEssay",
        component: () => import("../views/MyEssay.vue"),
    },
    {
        path: "/search",
        name: "search",
        component: () => import("../views/SearchView.vue"),
    },
];

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes,
});

router.beforeEach((to, from, next) => {
    if (document.cookie) {
        let arr = document.cookie.split("; ");
        interface objData {
            account: string;
            [key: string]: string;
        }
        let obj: objData = {
            account: "",
        };
        arr.forEach((item) => {
            let keyName = item.split("=")[0];
            let keyVal = item.split("=")[1];
            obj[keyName] = keyVal;
        });

        if (!obj.account) {
            if (to.path != "/" && to.path != "/principalSheet" && to.path != "/loginRegistration") {
                router.push({ name: "loginRegistration" });
                showFailToast("请先登录");
            }
        }
    } else {
        if (to.path != "/" && to.path != "/principalSheet" && to.path != "/loginRegistration") {
            router.push({ name: "loginRegistration" });
            showFailToast("请先登录");
        }
    }
    next();
});
export default router;
